import json
import requests

class CubeServices(object):
    @staticmethod
    def fetchBoradData(conditions,dimension_row,measure_ids,time_range,compared_time_range):
        """_summary_

        Args:
            conditions (_type_): 查询条件 {1:"1,2,3"}
            dimension_row (_type_): 查询维度 ["10805"] or None
            measure_ids (_type_): 指标id [103535, 102403, 102405, 102409]
            time_range (_type_): 时间范围 "2025/04/01 00:00:00 - 2025/04/18 23:59:59"
            compared_time_range (_type_): 对比的时间范围 "2025/02/04 00:00:00 - 2025/02/28 23:59:59"

        Returns:
            _type_: _description_
        """
        print("time_rangeL:",time_range)
        url = "https://cube.xiujiadian.com/board/advanced/ajaxBoard"
        headers = {
            "accept": "application/json, text/javascript, */*; q=0.01",
            "content-type":"application/json",
            "cookie":"prod.zmn.id=63f35396-a1ae-4439-a217-07618ea6be19"
        }
        data = {
            "conditions":conditions,
            "measureIds":measure_ids,
            "config":{
                "datasetId": 1000,  # 工单数据集
                "timeRange": time_range, 
                "timeColumn": "enter_time", # 下单时间
                "timeColumnSco": "",
                "dimensionCol": "",
                "dimensionRow": dimension_row,
                "compareMode": "4" if compared_time_range else "1",
                "comparedTimeRange": compared_time_range,
                "subNumber": "",
                "debug": "false"
                }
        }
        res = requests.post(url,headers=headers,json=data)
        return res.text

    @staticmethod
    def format_cube_data(data):
        """格式化cube返回数据为markdown格式

        Args:
            data (_type_): _description_

        Returns:
            _type_: _description_
        """
        data = json.loads(data)
        itemRows = data["data"]["itemRows"]
        totalRow = data["data"]["totalRow"]
        config = data["data"]["config"]
        compareMode = config["compareMode"]
        compareMode = False if compareMode == 1 else True
        measures = config["measures"]
        measureIds = config["measureIds"]
        yValues = config["yValues"]
        yTexts = config["yTexts"]
        yTitles = config["yTitles"]
        y_dict = {k:v for k,v in zip(yValues,yTexts)}
        
        measure_dict = {
        
        }
        T = ""
        T_h = "|-"
        for index,measure in enumerate(measures):
            measure_name = measure[0]
            measure_id = measureIds[index]
            measure_dict[measure_id] = measure_name
            T_h += f"|**{measure_name}**"
            if compareMode:T_h += "|" * 2
        print(measure_dict[102001])
        T_h += "|"
        T+=T_h
        T+="\n"
        
        if compareMode:
            _ = "|-" + "|-" * 3 * len(measures) + "|"
            _+= "\n"
            _+= "|-" + '|*本期*|*上期*|*增长率*' * len(measures) + "|"
        else:
            _ = "|-" + "|-" * 1 * len(measures) + "|"
        
        T+=_
        T+="\n" 
        
        

        for item_id,item_value in itemRows.items():
            item_name = y_dict.get(item_id)
            T_line = "|" + item_name
            for index,measure in enumerate(measures):
                measure_name = measure[0]
                measure_id = measureIds[index] 
                measure_value = item_value[f"x-{measure_id}"]
                # print(item_name,measure_id,measure_name)
                T_line += f"|{measure_value[0]}"
                if compareMode:
                    T_line += f"|{measure_value[-1][0]}"
                    T_line += f"|{measure_value[-1][-1]}"
            T_line += "|\n"
            T+=T_line
        

        # for item_id,item_value in itemRows.items():
        #     item_name = y_dict.get(item_id)
        #     T_line = "|" + item_name
        #     for measure_x_id,measure_value in item_value.items():
        #         measure_id = int(measure_x_id.replace("x-",""))
        #         measure_name = measure_dict[measure_id]
        #         # print(item_name,measure_id,measure_name)
        #         T_line += f"|{measure_value[0]}"
        #         if compareMode:
        #             T_line += f"|{measure_value[-1][0]}"
        #             T_line += f"|{measure_value[-1][-1]}"
        #     T_line += "|\n"
        #     T+=T_line
        
        return T

    @staticmethod
    def format_cube_ordercirc_data(data):
        """格式化订单流转的数据为markdown形式

        Args:
            data (_type_): _description_
        """

if __name__ == "__main__":
    measure_ids = [102001,102002,102102,102203,2000417,102246,102401,102502,800099,800108,2001669,2001391,102206,800108,800102,800103,800109,102431,102442,104114,104214,800110,800102,800103,800109,102403,102247,102248,102208,102443,800111,800112,102209,102249,102250,102409,102708,800113,2000944,2001005,2001692,2001693,2001694,2001695]
    # measure_ids = [102001, 102002, 2000417, 102102]
    data = {
  "conditions": {
    "10032": "500100",
    "10043": "1013,1016"
  },
  "timeRange": "2025/04/17 00:00:00 - 2025/04/17 23:59:59",
  "comparedTimeRange": "2025/04/16 00:00:00 - 2025/04/16 23:59:59"
}


    data = CubeServices.fetchBoradData(
        conditions=data["conditions"],
        dimension_row=None,
        measure_ids=measure_ids,
        time_range=data["timeRange"],
        compared_time_range=data["comparedTimeRange"]
    )
    print(data)
    data = CubeServices.format_cube_data(data)
    print(data)